using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FlickrNet;

namespace SmilingGoat.WindowsLiveWriter.Flickr
{
    public class InsertFlickrImageForm : Form
    {
        #region Globals and Constants
        private const int PER_PAGE = 8;
        private const string FLICKR_SIGNUP = "http://www.flickr.com/signup";
        private const string FLICKR_URL = "http://www.flickr.com";
        #endregion

        #region Member Variables

        private Label label2;
        private ComboBox dropDownImageSizes;
        private GroupBox groupBox1;
        private ComboBox dropDownAlignment;
        private Label label3;
        private NumericUpDown verticalPadding;
        private Label label6;
        private NumericUpDown borderThickness;
        private Label label5;
        private NumericUpDown horizontalPadding;
        private Label label4;
        private int _currentPage = 1;
        private FlickrNet.Flickr flickrProxy;
        private string _userId = string.Empty;
        private FlickrNet.Photo _currentPhoto;
        private string _srcUrl;
        private TextBox textBoxCssClass;
        private Label label7;
        private CheckBox checkHyperLink;
        private Label label8;
        private TextBox textBoxTagFilter;
        private PictureBox _selectedPicture;
        private PictureBox pictureBox5;
        private Label label9;
        private LinkLabel linkLabel1;
        private ToolTip toolTip1;
        private PictureBox pictureBox6;
        private long _totalPages;
        private StatusStrip statusStrip1;
        private Button button1;
        private ToolTip toolTip2;
        private ImageList imageListing;
        private ListView listView1;
        private ComboBox photosetList;
        private Label label10;
        private Button buttonGetImages;
        private Button refreshSet;
        private Button pagePrevious;
        private Button pageNext;
        private bool _images = false;
        private ToolTip tipSets;
        private ToolTip tipUser;
        private Button button2;
        private ToolStripStatusLabel statusLabel;
        private ToolStripStatusLabel statusPictureCount;
        private ToolStripStatusLabel statusPage;
        private ToolStripStatusLabel toolStripStatusLabel1;
        private BackgroundWorker imageProcessor;
        private ToolStripProgressBar progressBar;
        private BackgroundWorker setProcessor;
        private string _set = string.Empty;
        #endregion

        #region Public Properties
        public string FlickrUserId
        {
            get { return _userId; }
        }
        public string Alignment
        {
            get { return dropDownAlignment.Text.Trim(); }
        }
        public bool EnableHyperLink
        {
            get { return checkHyperLink.Checked; }
        }
        public string CssClass
        {
            get { return textBoxCssClass.Text.Trim(); }
        }

        public string FlickrUserName
        {
            get { return textboxFlickrUserName.Text.Trim(); }
        }       

        public string BorderThickness
        {
            get { return borderThickness.Value.ToString().Trim(); }
        }        

        public string HorizontalPadding
        {
            get { return horizontalPadding.Value.ToString().Trim(); }
        }        

        public string VerticalPadding
        {
            get { return verticalPadding.Value.ToString().Trim(); }
        }       
    
        public FlickrNet.Photo SelectedPhoto
        {
            get { return _currentPhoto; }
        }

        public string ImageSourceUrl
        {
            get { return _srcUrl; }
        }
        #endregion

        #region Required Designer Code
        // NOTE: This is here because we are using VS2005 to develop and MSBee to compile
        // At this time, MSBee did not support partial classes

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InsertFlickrImageForm));
            this.buttonInsert = new System.Windows.Forms.Button();
            this.buttonCancel = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.textboxFlickrUserName = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.dropDownImageSizes = new System.Windows.Forms.ComboBox();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.checkHyperLink = new System.Windows.Forms.CheckBox();
            this.textBoxCssClass = new System.Windows.Forms.TextBox();
            this.label7 = new System.Windows.Forms.Label();
            this.verticalPadding = new System.Windows.Forms.NumericUpDown();
            this.label6 = new System.Windows.Forms.Label();
            this.borderThickness = new System.Windows.Forms.NumericUpDown();
            this.label5 = new System.Windows.Forms.Label();
            this.horizontalPadding = new System.Windows.Forms.NumericUpDown();
            this.label4 = new System.Windows.Forms.Label();
            this.dropDownAlignment = new System.Windows.Forms.ComboBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label8 = new System.Windows.Forms.Label();
            this.textBoxTagFilter = new System.Windows.Forms.TextBox();
            this.label9 = new System.Windows.Forms.Label();
            this.linkLabel1 = new System.Windows.Forms.LinkLabel();
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.buttonGetImages = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            this.pictureBox6 = new System.Windows.Forms.PictureBox();
            this.pictureBox5 = new System.Windows.Forms.PictureBox();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.progressBar = new System.Windows.Forms.ToolStripProgressBar();
            this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
            this.statusLabel = new System.Windows.Forms.ToolStripStatusLabel();
            this.statusPictureCount = new System.Windows.Forms.ToolStripStatusLabel();
            this.statusPage = new System.Windows.Forms.ToolStripStatusLabel();
            this.toolTip2 = new System.Windows.Forms.ToolTip(this.components);
            this.imageListing = new System.Windows.Forms.ImageList(this.components);
            this.listView1 = new System.Windows.Forms.ListView();
            this.photosetList = new System.Windows.Forms.ComboBox();
            this.label10 = new System.Windows.Forms.Label();
            this.refreshSet = new System.Windows.Forms.Button();
            this.pagePrevious = new System.Windows.Forms.Button();
            this.pageNext = new System.Windows.Forms.Button();
            this.tipSets = new System.Windows.Forms.ToolTip(this.components);
            this.button2 = new System.Windows.Forms.Button();
            this.tipUser = new System.Windows.Forms.ToolTip(this.components);
            this.imageProcessor = new System.ComponentModel.BackgroundWorker();
            this.setProcessor = new System.ComponentModel.BackgroundWorker();
            this.groupBox1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.verticalPadding)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.borderThickness)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.horizontalPadding)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox6)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).BeginInit();
            this.statusStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // buttonInsert
            // 
            this.buttonInsert.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.buttonInsert.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.buttonInsert.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.buttonInsert.Location = new System.Drawing.Point(16, 495);
            this.buttonInsert.Name = "buttonInsert";
            this.buttonInsert.Size = new System.Drawing.Size(88, 23);
            this.buttonInsert.TabIndex = 12;
            this.buttonInsert.Text = "Insert Image";
            this.buttonInsert.Click += new System.EventHandler(this.buttonInsert_Click);
            // 
            // buttonCancel
            // 
            this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.buttonCancel.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.buttonCancel.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.buttonCancel.Location = new System.Drawing.Point(122, 495);
            this.buttonCancel.Name = "buttonCancel";
            this.buttonCancel.Size = new System.Drawing.Size(88, 23);
            this.buttonCancel.TabIndex = 13;
            this.buttonCancel.Text = "Cancel";
            this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(294, 46);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(93, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "Flickr user name:";
            // 
            // textboxFlickrUserName
            // 
            this.textboxFlickrUserName.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.textboxFlickrUserName.Location = new System.Drawing.Point(393, 46);
            this.textboxFlickrUserName.Name = "textboxFlickrUserName";
            this.textboxFlickrUserName.Size = new System.Drawing.Size(211, 22);
            this.textboxFlickrUserName.TabIndex = 1;
            this.textboxFlickrUserName.TextChanged += new System.EventHandler(this.textboxFlickrUserName_TextChanged);
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(17, 427);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(68, 13);
            this.label2.TabIndex = 0;
            this.label2.Text = "Picture Size:";
            // 
            // dropDownImageSizes
            // 
            this.dropDownImageSizes.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.dropDownImageSizes.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dropDownImageSizes.Items.AddRange(new object[] {
            "Thumbnail",
            "Small",
            "Medium",
            "Large"});
            this.dropDownImageSizes.Location = new System.Drawing.Point(89, 424);
            this.dropDownImageSizes.Name = "dropDownImageSizes";
            this.dropDownImageSizes.Size = new System.Drawing.Size(121, 21);
            this.dropDownImageSizes.TabIndex = 10;
            this.dropDownImageSizes.SelectedIndexChanged += new System.EventHandler(this.GenericUpdateChange);
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.checkHyperLink);
            this.groupBox1.Controls.Add(this.textBoxCssClass);
            this.groupBox1.Controls.Add(this.label7);
            this.groupBox1.Controls.Add(this.verticalPadding);
            this.groupBox1.Controls.Add(this.label6);
            this.groupBox1.Controls.Add(this.borderThickness);
            this.groupBox1.Controls.Add(this.label5);
            this.groupBox1.Controls.Add(this.horizontalPadding);
            this.groupBox1.Controls.Add(this.label4);
            this.groupBox1.Controls.Add(this.dropDownAlignment);
            this.groupBox1.Controls.Add(this.label3);
            this.groupBox1.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox1.Location = new System.Drawing.Point(278, 412);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(326, 106);
            this.groupBox1.TabIndex = 11;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Layout";
            // 
            // checkHyperLink
            // 
            this.checkHyperLink.Checked = true;
            this.checkHyperLink.CheckState = System.Windows.Forms.CheckState.Checked;
            this.checkHyperLink.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.checkHyperLink.Location = new System.Drawing.Point(162, 79);
            this.checkHyperLink.Name = "checkHyperLink";
            this.checkHyperLink.Size = new System.Drawing.Size(143, 17);
            this.checkHyperLink.TabIndex = 6;
            this.checkHyperLink.Text = "Include link to image";
            // 
            // textBoxCssClass
            // 
            this.textBoxCssClass.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.textBoxCssClass.Location = new System.Drawing.Point(73, 74);
            this.textBoxCssClass.Name = "textBoxCssClass";
            this.textBoxCssClass.Size = new System.Drawing.Size(80, 22);
            this.textBoxCssClass.TabIndex = 5;
            this.textBoxCssClass.TextChanged += new System.EventHandler(this.GenericUpdateChange);
            // 
            // label7
            // 
            this.label7.AutoSize = true;
            this.label7.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label7.Location = new System.Drawing.Point(7, 74);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(58, 13);
            this.label7.TabIndex = 0;
            this.label7.Text = "CSS Class:";
            // 
            // verticalPadding
            // 
            this.verticalPadding.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.verticalPadding.Location = new System.Drawing.Point(272, 45);
            this.verticalPadding.Name = "verticalPadding";
            this.verticalPadding.Size = new System.Drawing.Size(46, 22);
            this.verticalPadding.TabIndex = 4;
            this.verticalPadding.ValueChanged += new System.EventHandler(this.GenericUpdateChange);
            // 
            // label6
            // 
            this.label6.AutoSize = true;
            this.label6.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label6.Location = new System.Drawing.Point(159, 49);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(91, 13);
            this.label6.TabIndex = 0;
            this.label6.Text = "Vertical spacing:";
            // 
            // borderThickness
            // 
            this.borderThickness.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.borderThickness.Location = new System.Drawing.Point(103, 45);
            this.borderThickness.Name = "borderThickness";
            this.borderThickness.Size = new System.Drawing.Size(50, 22);
            this.borderThickness.TabIndex = 3;
            this.borderThickness.ValueChanged += new System.EventHandler(this.GenericUpdateChange);
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label5.Location = new System.Drawing.Point(7, 49);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(96, 13);
            this.label5.TabIndex = 0;
            this.label5.Text = "Border thickness:";
            // 
            // horizontalPadding
            // 
            this.horizontalPadding.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.horizontalPadding.Location = new System.Drawing.Point(272, 17);
            this.horizontalPadding.Name = "horizontalPadding";
            this.horizontalPadding.Size = new System.Drawing.Size(46, 22);
            this.horizontalPadding.TabIndex = 2;
            this.horizontalPadding.ValueChanged += new System.EventHandler(this.GenericUpdateChange);
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label4.Location = new System.Drawing.Point(159, 20);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(107, 13);
            this.label4.TabIndex = 0;
            this.label4.Text = "Horizontal spacing:";
            // 
            // dropDownAlignment
            // 
            this.dropDownAlignment.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.dropDownAlignment.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dropDownAlignment.Items.AddRange(new object[] {
            "None",
            "Left",
            "Right",
            "TextTop",
            "Middle",
            "TextBottom"});
            this.dropDownAlignment.Location = new System.Drawing.Point(73, 17);
            this.dropDownAlignment.Name = "dropDownAlignment";
            this.dropDownAlignment.Size = new System.Drawing.Size(80, 21);
            this.dropDownAlignment.TabIndex = 1;
            this.dropDownAlignment.SelectedIndexChanged += new System.EventHandler(this.GenericUpdateChange);
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label3.Location = new System.Drawing.Point(7, 20);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(63, 13);
            this.label3.TabIndex = 0;
            this.label3.Text = "Alignment:";
            // 
            // label8
            // 
            this.label8.AutoSize = true;
            this.label8.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label8.Location = new System.Drawing.Point(255, 77);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(132, 13);
            this.label8.TabIndex = 0;
            this.label8.Text = "Tags (comma separated):";
            // 
            // textBoxTagFilter
            // 
            this.textBoxTagFilter.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.textBoxTagFilter.Location = new System.Drawing.Point(393, 74);
            this.textBoxTagFilter.Name = "textBoxTagFilter";
            this.textBoxTagFilter.Size = new System.Drawing.Size(88, 22);
            this.textBoxTagFilter.TabIndex = 5;
            this.textBoxTagFilter.TextChanged += new System.EventHandler(this.textBoxTagFilter_TextChanged);
            // 
            // label9
            // 
            this.label9.AutoSize = true;
            this.label9.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label9.Location = new System.Drawing.Point(471, 9);
            this.label9.Name = "label9";
            this.label9.Size = new System.Drawing.Size(79, 13);
            this.label9.TabIndex = 0;
            this.label9.Text = "New to Flickr?";
            this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // linkLabel1
            // 
            this.linkLabel1.AutoSize = true;
            this.linkLabel1.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.linkLabel1.Location = new System.Drawing.Point(551, 9);
            this.linkLabel1.Name = "linkLabel1";
            this.linkLabel1.Size = new System.Drawing.Size(53, 13);
            this.linkLabel1.TabIndex = 0;
            this.linkLabel1.TabStop = true;
            this.linkLabel1.Text = "Signup...";
            this.linkLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
            // 
            // toolTip1
            // 
            this.toolTip1.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info;
            this.toolTip1.ToolTipTitle = "Searching";
            // 
            // buttonGetImages
            // 
            this.buttonGetImages.Image = global::SmilingGoat.WindowsLiveWriter.Flickr.Properties.Resources.search16;
            this.buttonGetImages.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.buttonGetImages.Location = new System.Drawing.Point(515, 74);
            this.buttonGetImages.Name = "buttonGetImages";
            this.buttonGetImages.Size = new System.Drawing.Size(26, 23);
            this.buttonGetImages.TabIndex = 7;
            this.buttonGetImages.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.buttonGetImages.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
            this.toolTip1.SetToolTip(this.buttonGetImages, "Click here to search the Flickr user account for images.\r\n\r\nYou can enter tags to" +
                    " filter (comma separated) or leave\r\nit blank to show all.");
            this.buttonGetImages.Click += new System.EventHandler(this.buttonGetImages_Click);
            // 
            // button1
            // 
            this.button1.AutoSize = true;
            this.button1.Image = global::SmilingGoat.WindowsLiveWriter.Flickr.Properties.Resources.tag1;
            this.button1.Location = new System.Drawing.Point(487, 74);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(26, 23);
            this.button1.TabIndex = 6;
            this.button1.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
            this.toolTip2.SetToolTip(this.button1, "Click here to retrieve a list of tags for the Flickr user");
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // pictureBox6
            // 
            this.pictureBox6.Cursor = System.Windows.Forms.Cursors.Help;
            this.pictureBox6.Image = global::SmilingGoat.WindowsLiveWriter.Flickr.Properties.Resources.Info;
            this.pictureBox6.Location = new System.Drawing.Point(182, 12);
            this.pictureBox6.Name = "pictureBox6";
            this.pictureBox6.Size = new System.Drawing.Size(16, 16);
            this.pictureBox6.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pictureBox6.TabIndex = 20;
            this.pictureBox6.TabStop = false;
            this.pictureBox6.Click += new System.EventHandler(this.pictureBox6_Click);
            // 
            // pictureBox5
            // 
            this.pictureBox5.Cursor = System.Windows.Forms.Cursors.Hand;
            this.pictureBox5.Image = global::SmilingGoat.WindowsLiveWriter.Flickr.Properties.Resources.flickr_gamma;
            this.pictureBox5.Location = new System.Drawing.Point(19, 13);
            this.pictureBox5.Name = "pictureBox5";
            this.pictureBox5.Size = new System.Drawing.Size(157, 43);
            this.pictureBox5.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pictureBox5.TabIndex = 15;
            this.pictureBox5.TabStop = false;
            this.pictureBox5.Click += new System.EventHandler(this.pictureBox5_Click);
            // 
            // statusStrip1
            // 
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.progressBar,
            this.toolStripStatusLabel1,
            this.statusLabel,
            this.statusPictureCount,
            this.statusPage});
            this.statusStrip1.Location = new System.Drawing.Point(0, 526);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(621, 22);
            this.statusStrip1.SizingGrip = false;
            this.statusStrip1.TabIndex = 0;
            // 
            // progressBar
            // 
            this.progressBar.Name = "progressBar";
            this.progressBar.Size = new System.Drawing.Size(100, 16);
            // 
            // toolStripStatusLabel1
            // 
            this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
            this.toolStripStatusLabel1.Size = new System.Drawing.Size(42, 17);
            this.toolStripStatusLabel1.Text = "Status:";
            // 
            // statusLabel
            // 
            this.statusLabel.Name = "statusLabel";
            this.statusLabel.Size = new System.Drawing.Size(0, 17);
            // 
            // statusPictureCount
            // 
            this.statusPictureCount.Name = "statusPictureCount";
            this.statusPictureCount.Size = new System.Drawing.Size(0, 17);
            // 
            // statusPage
            // 
            this.statusPage.Name = "statusPage";
            this.statusPage.Size = new System.Drawing.Size(0, 17);
            // 
            // toolTip2
            // 
            this.toolTip2.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info;
            this.toolTip2.ToolTipTitle = "Flickr Tags";
            // 
            // imageListing
            // 
            this.imageListing.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
            this.imageListing.ImageSize = new System.Drawing.Size(102, 102);
            this.imageListing.TransparentColor = System.Drawing.Color.Transparent;
            // 
            // listView1
            // 
            this.listView1.BackColor = System.Drawing.Color.White;
            this.listView1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.listView1.CausesValidation = false;
            this.listView1.Cursor = System.Windows.Forms.Cursors.Hand;
            this.listView1.LargeImageList = this.imageListing;
            this.listView1.Location = new System.Drawing.Point(16, 101);
            this.listView1.Margin = new System.Windows.Forms.Padding(0);
            this.listView1.MultiSelect = false;
            this.listView1.Name = "listView1";
            this.listView1.ShowGroups = false;
            this.listView1.Size = new System.Drawing.Size(588, 308);
            this.listView1.TabIndex = 0;
            this.listView1.UseCompatibleStateImageBehavior = false;
            this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
            // 
            // photosetList
            // 
            this.photosetList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.photosetList.FormattingEnabled = true;
            this.photosetList.Location = new System.Drawing.Point(48, 74);
            this.photosetList.Name = "photosetList";
            this.photosetList.Size = new System.Drawing.Size(150, 21);
            this.photosetList.TabIndex = 2;
            // 
            // label10
            // 
            this.label10.AutoSize = true;
            this.label10.Location = new System.Drawing.Point(17, 77);
            this.label10.Name = "label10";
            this.label10.Size = new System.Drawing.Size(31, 13);
            this.label10.TabIndex = 0;
            this.label10.Text = "Sets:";
            // 
            // refreshSet
            // 
            this.refreshSet.Image = global::SmilingGoat.WindowsLiveWriter.Flickr.Properties.Resources.blueArrowDown16;
            this.refreshSet.Location = new System.Drawing.Point(230, 74);
            this.refreshSet.Name = "refreshSet";
            this.refreshSet.Size = new System.Drawing.Size(26, 23);
            this.refreshSet.TabIndex = 4;
            this.tipSets.SetToolTip(this.refreshSet, "When a photoset is selected, this will retrieve\r\n the images for that photoset");
            this.refreshSet.UseVisualStyleBackColor = true;
            this.refreshSet.Click += new System.EventHandler(this.refreshSet_Click);
            // 
            // pagePrevious
            // 
            this.pagePrevious.Enabled = false;
            this.pagePrevious.Image = global::SmilingGoat.WindowsLiveWriter.Flickr.Properties.Resources.blueArrowLeft16;
            this.pagePrevious.Location = new System.Drawing.Point(550, 74);
            this.pagePrevious.Name = "pagePrevious";
            this.pagePrevious.Size = new System.Drawing.Size(26, 23);
            this.pagePrevious.TabIndex = 8;
            this.pagePrevious.UseVisualStyleBackColor = true;
            this.pagePrevious.Click += new System.EventHandler(this.pagePrevious_Click);
            // 
            // pageNext
            // 
            this.pageNext.Enabled = false;
            this.pageNext.Image = global::SmilingGoat.WindowsLiveWriter.Flickr.Properties.Resources.blueArrowRight16;
            this.pageNext.Location = new System.Drawing.Point(578, 74);
            this.pageNext.Name = "pageNext";
            this.pageNext.Size = new System.Drawing.Size(26, 23);
            this.pageNext.TabIndex = 9;
            this.pageNext.UseVisualStyleBackColor = true;
            this.pageNext.Click += new System.EventHandler(this.pageNext_Click);
            // 
            // tipSets
            // 
            this.tipSets.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info;
            this.tipSets.ToolTipTitle = "Photosets";
            // 
            // button2
            // 
            this.button2.Image = global::SmilingGoat.WindowsLiveWriter.Flickr.Properties.Resources.blackRefresh24;
            this.button2.Location = new System.Drawing.Point(201, 74);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(26, 23);
            this.button2.TabIndex = 3;
            this.tipSets.SetToolTip(this.button2, "Refreshes/retrieves a list of photosets for the user account.");
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // tipUser
            // 
            this.tipUser.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info;
            this.tipUser.ToolTipTitle = "User Information";
            // 
            // imageProcessor
            // 
            this.imageProcessor.WorkerReportsProgress = true;
            this.imageProcessor.DoWork += new System.ComponentModel.DoWorkEventHandler(this.imageProcessor_DoWork);
            this.imageProcessor.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.imageProcessor_RunWorkerCompleted);
            this.imageProcessor.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.imageProcessor_ProgressChanged);
            // 
            // setProcessor
            // 
            this.setProcessor.WorkerReportsProgress = true;
            this.setProcessor.DoWork += new System.ComponentModel.DoWorkEventHandler(this.setProcessor_DoWork);
            // 
            // InsertFlickrImageForm
            // 
            this.ClientSize = new System.Drawing.Size(621, 548);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.pageNext);
            this.Controls.Add(this.pagePrevious);
            this.Controls.Add(this.refreshSet);
            this.Controls.Add(this.label10);
            this.Controls.Add(this.photosetList);
            this.Controls.Add(this.listView1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.statusStrip1);
            this.Controls.Add(this.pictureBox6);
            this.Controls.Add(this.linkLabel1);
            this.Controls.Add(this.label9);
            this.Controls.Add(this.pictureBox5);
            this.Controls.Add(this.textBoxTagFilter);
            this.Controls.Add(this.label8);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.dropDownImageSizes);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.buttonGetImages);
            this.Controls.Add(this.textboxFlickrUserName);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.buttonCancel);
            this.Controls.Add(this.buttonInsert);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "InsertFlickrImageForm";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Insert Flickr Image";
            
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.verticalPadding)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.borderThickness)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.horizontalPadding)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox6)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).EndInit();
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        void textBoxTagFilter_TextChanged(object sender, EventArgs e)
        {
            _currentPage = 1;
        }

        private System.Windows.Forms.Button buttonInsert;
        private System.Windows.Forms.Button buttonCancel;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textboxFlickrUserName;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        #endregion

        #region Constructors
        public InsertFlickrImageForm(FlickrContext context)
        {
            InitializeComponent();
            this.dropDownAlignment.SelectedIndex = 0;
            this.dropDownImageSizes.SelectedIndex = 2;

            textboxFlickrUserName.Focus();
            textboxFlickrUserName.Text = context.FlickrUserName.Trim();
            textBoxTagFilter.Text = context.FlickrTags.Trim();

            // TODO: Consider threaded start of init
            System.Threading.Thread init = new System.Threading.Thread(new System.Threading.ThreadStart(EnsureFlickrNet));
            init.Start();
        }

        private void EnsureFlickrNet()
        {
            if (flickrProxy == null)
            {
                FlickrNet.Flickr.CacheDisabled = true;
                
                System.Resources.ResourceManager mgr = new System.Resources.ResourceManager(typeof(SmilingGoat.WindowsLiveWriter.Flickr.Properties.Resources));
                flickrProxy = new FlickrNet.Flickr(mgr.GetString("ApiKey"), mgr.GetString("SharedSecret"));

                // Leverage proxy settings if they are there.
                System.Net.WebProxy proxySettings = (System.Net.WebProxy)WindowsLive.Writer.Api.PluginHttpRequest.GetWriterProxy();
                if (proxySettings != null)
                {
                    flickrProxy.Proxy = proxySettings;
                }
            }
        }

        private void InitialFlickrRetrieval()
        {
            /*EnsureFlickrNet();
            if (LoginUser())
            {
                // get photos
                UpdateStatus("Retrieving recent images...");
                DrawRetrievedImages();
                UpdateStatus(string.Empty); // clear the status message
            }*/
            DrawRetrievedImages();
        } 
        #endregion

        #region Event Handlers
        /// <summary>
        /// Cancels the modal dialog to insert a Flickr Image.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            base.DialogResult = DialogResult.Cancel;
        }

        /// <summary>
        /// The OK function of the modal dialog resulting in letting the ContentSource know the action is complete.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonInsert_Click(object sender, EventArgs e)
        {
            if (_currentPhoto == null)
            {
                MessageBox.Show("No image selected.  Please choose an image or cancel to continue.", "No image selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else
            {
                base.DialogResult = DialogResult.OK;
            }
        }

        /// <summary>
        /// A generic update EventHandler that is leveraged by several OnChanged events throughout 
        /// the control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GenericUpdateChange(object sender, EventArgs e)
        {
            if (_currentPhoto != null)
            {
                UpdateCurrentImageData();
            }
        }

        private void DrawRetrievedImages()
        {
            FlickrNet.PhotoSearchOptions options = new FlickrNet.PhotoSearchOptions(_userId);
            options.PerPage = PER_PAGE;
            options.Page = _currentPage;
            options.Tags = FlickrPluginHelper.CleanTagFilter(textBoxTagFilter.Text.Trim());

            ClearImageList();

            // reset the selected picture
            if (_selectedPicture != null)
            {
                _currentPhoto = null;
            }

            FlickrNet.Photos fPhotos = null;

            try
            {
                if (_set.Length > 0)
                {
                    Photo[] photoArray = flickrProxy.PhotosetsGetPhotos(_set);
                    Photos ps = new Photos();
                    for (int i = 0; i < photoArray.Length; i++)
                    {
                        ps.PhotoCollection.Add(photoArray[i]);
                    }
                    fPhotos = ps;
                }
                else
                {
                    fPhotos = flickrProxy.PhotosSearch(options);
                }
                statusPictureCount.Text = string.Format("Image Count: {0}", fPhotos.TotalPhotos.ToString());
                statusPage.Text = string.Format("Page {0} of {1}", _currentPage.ToString(), fPhotos.TotalPages.ToString());
            }
            catch (FlickrNet.FlickrException ex)
            {
                if (ex.Code == 9999)
                {
                    MessageBox.Show("Flickr could not be contacted.  The requested timed out.  \nPlease ensure your internet connection is still valid.", "Flickr Connection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            _totalPages = fPhotos.TotalPages;
            if (_totalPages > 1)
            {
                pageNext.Enabled = true;
            }

            progressBar.Maximum = fPhotos.PhotoCollection.Length - 1;

            if (fPhotos.PhotoCollection.Count > 0)
            {
                _images = true;

                for (int i = 0; i < fPhotos.PhotoCollection.Count; i++)
                {
                    Image img = FlickrPluginHelper.ScaleToFixedSize(FlickrPluginHelper.GetImageFromUrl(fPhotos.PhotoCollection[i].ThumbnailUrl), imageListing.ImageSize.Width, imageListing.ImageSize.Height, 0, Color.Transparent);
                    imageListing.Images.Add(img);
                    ListViewItem item = new ListViewItem();
                    item.Tag = fPhotos.PhotoCollection[i];
                    item.Text = fPhotos.PhotoCollection[i].Title;
                    item.ImageIndex = i;
                    listView1.Items.Add(item);
                    imageProcessor.ReportProgress(i);
                }
            }
        }

        private void ClearImageList()
        {
            imageListing.Images.Clear();
            listView1.Items.Clear();
        }

        /// <summary>
        /// EventHandler for retrieving the initial set of Flickr images for the Flickr user name.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonGetImages_Click(object sender, EventArgs e)
        {
            _set = string.Empty;

            EnsureFlickrNet();
            if (LoginUser())
            {
                StartImageProcessor();
            }
        }

        private void StartImageProcessor()
        {
            if (this.imageProcessor.IsBusy)
            {
                imageProcessor.CancelAsync();
            }
            while (imageProcessor.CancellationPending)
            {
                Application.DoEvents();
            }
            imageProcessor.RunWorkerAsync();
        }
        #endregion

        #region Overrides
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #endregion

        #region Mini Helper Methods
        private bool LoginUser()
        {
            if (string.IsNullOrEmpty(_userId))
            {
                UpdateStatus("Validating user...");
                // make sure at least something is there
                // let's not waste our time if nobody put a login name
                if (textboxFlickrUserName.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Please enter a Flickr login (email address)", "No Flickr Login", MessageBoxButtons.OK);
                    textboxFlickrUserName.SelectAll();
                    textboxFlickrUserName.Focus();
                    return false;
                }

                try
                {

                    string userId = string.Empty;
                    FlickrNet.FoundUser user;

                    user = FlickrPluginHelper.FindUserByEmailOrName(flickrProxy, textboxFlickrUserName.Text.Trim());
                    _userId = user.UserId;

                    return true;
                }
                catch (FlickrNet.FlickrException ex)
                {
                    UpdateStatus(string.Empty);
                    if (ex.Code == 1)  // user not found
                    {
                        MessageBox.Show("Flickr user not found.  Please ensure it is either the Flickr email address or correct Flickr user name.", "Flickr User Not Found", MessageBoxButtons.OK);
                        return false;
                    }

                    if (ex.Code == 9999) // HttpTimeout
                    {
                        MessageBox.Show("Flickr could not be contacted.  The requested timed out.  \nPlease ensure your internet connection is still valid.", "Flickr Connection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                    return false;
                }
                finally
                {
                    UpdateStatus(string.Empty);
                }
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// Simple method to help update the status area.
        /// </summary>
        /// <param name="message">The status message to display.</param>
        private void UpdateStatus(string message)
        {
            statusLabel.Text = message;
            if (message.Length < 1) // default the curser back
            {
                Cursor.Current = Cursors.Default;
                statusLabel.Text = "Idle";
            }
            else // we are actually doing something, let's pause the cursor
            {
                Cursor.Current = Cursors.WaitCursor;
            }
        }

        /// <summary>
        /// Method to update member variables with data regarding the selected image and the layout properties.
        /// </summary>
        private void UpdateCurrentImageData()
        {
            ChangeImageSourceUrl();
        }

        /// <summary>
        /// Method to change the image reference (src) url for the Html content.
        /// </summary>
        private void ChangeImageSourceUrl()
        {
            switch (dropDownImageSizes.Text)
            {
                case "Thumbnail":
                    _srcUrl = _currentPhoto.ThumbnailUrl;
                    break;
                case "Small":
                    _srcUrl = _currentPhoto.SmallUrl;
                    break;
                case "Large":
                    _srcUrl = _currentPhoto.LargeUrl;
                    break;
                default:
                    _srcUrl = _currentPhoto.MediumUrl;
                    break;
            }
        }
        #endregion

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FlickrPluginHelper.GotoUrl(FLICKR_SIGNUP);
        }

        private void pictureBox5_Click(object sender, EventArgs e)
        {
            FlickrPluginHelper.GotoUrl(FLICKR_URL);
        }

        private void pictureBox6_Click(object sender, EventArgs e)
        {
            AboutFlickrPlugin about = new AboutFlickrPlugin();
            about.ShowDialog();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (LoginUser())
            {

                UpdateStatus(string.Format("Retrieving tag list for {0}...", textboxFlickrUserName.Text.Trim()));

                FlickrNet.Tag[] tags = flickrProxy.TagsGetListUser(_userId);
                string selectedTags = string.Empty;

                using (TagList tagForm = new TagList(tags))
                {
                    System.Windows.Forms.DialogResult result = tagForm.ShowDialog();

                    if (result == DialogResult.OK)
                    {
                        textBoxTagFilter.Text = tagForm.SelectedTags;
                    }
                }

                UpdateStatus(string.Empty);
            }
        }

        private void textboxFlickrUserName_TextChanged(object sender, EventArgs e)
        {
            _userId = string.Empty;
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listView1.SelectedIndices.Count == 1)
            {
                FlickrNet.Photo p = (FlickrNet.Photo)listView1.Items[listView1.SelectedIndices[0]].Tag;
                _currentPhoto = p;
                ChangeImageSourceUrl();
            }
        }

        private void pagePrevious_Click(object sender, EventArgs e)
        {
            if (_images)
            {
                UpdateStatus(string.Format("Getting previous {0} images...", PER_PAGE.ToString()));

                if (_currentPage == 1)
                {
                    _currentPage = Convert.ToInt32(_totalPages);
                }
                else
                {
                    _currentPage--;
                    pageNext.Enabled = true;
                }

                StartImageProcessor();

                UpdateStatus(string.Empty);
            }
        }

        private void pageNext_Click(object sender, EventArgs e)
        {
            if (_images)
            {
                UpdateStatus(string.Format("Getting next {0} images...", PER_PAGE.ToString()));

                if (_currentPage == Convert.ToInt32(_totalPages))
                {
                    _currentPage = 1;
                    pagePrevious.Enabled = false;
                }
                else
                {
                    _currentPage++;
                    pagePrevious.Enabled = true;
                }

                StartImageProcessor();

                UpdateStatus(string.Empty);
            }
        }

        private void RefreshPhotosets()
        {
            photosetList.Items.Clear();

            Photosets sets = flickrProxy.PhotosetsGetList(_userId);

            photosetList.DataSource = sets.PhotosetCollection;
            photosetList.ValueMember = "PhotosetId";
            photosetList.DisplayMember = "Title";
        }

        private void refreshSet_Click(object sender, EventArgs e)
        {
            if ((string)photosetList.SelectedValue != string.Empty)
            {
                _set = (string)photosetList.SelectedValue;
                StartImageProcessor();
            }
            else
            {
                MessageBox.Show("This is to display the photoset selected.\nYou have not selected a photoset.", "No Photoset Selected", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.setProcessor.IsBusy)
            {
                setProcessor.CancelAsync();
            }
            while (setProcessor.CancellationPending)
            {
                Application.DoEvents();
            }
            setProcessor.RunWorkerAsync();
        }

        private void imageProcessor_DoWork(object sender, DoWorkEventArgs e)
        {
            UpdateStatus("Retrieving images from Flickr...");
            DrawRetrievedImages();
            UpdateStatus(string.Empty);
        }

        private void imageProcessor_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Visible = true;
            progressBar.Increment(1);

            if (e.ProgressPercentage == 100)
            {
                UpdateStatus(string.Empty);
            }
        }

        private void imageProcessor_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar.Value = 0;
            progressBar.Minimum = 0;
        }

        private void setProcessor_DoWork(object sender, DoWorkEventArgs e)
        {
            UpdateStatus("Retrieving photoset information...");
            EnsureFlickrNet();
            if (LoginUser())
            {
                RefreshPhotosets();
            }
            UpdateStatus(string.Empty);
        }
    }
}